package com.yeskery.nut.view.thymeleaf;

import com.yeskery.nut.core.NutException;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.Response;
import com.yeskery.nut.util.StringUtils;
import com.yeskery.nut.view.BaseHtmlView;
import com.yeskery.nut.view.WebRender;
import org.thymeleaf.TemplateEngine;

import java.util.Map;

/**
 * Thymeleaf视图对象
 * @author sprout
 * 2022-07-07 14:46
 */
public class ThymeleafView extends BaseHtmlView {

    /** 模板引擎 */
    private final TemplateEngine templateEngine;

    /** 模板名称 */
    private final String viewName;

    /**
     * 构建Thymeleaf视图对象
     * @param templateEngine 模板引擎
     * @param viewName 模板名称
     */
    public ThymeleafView(TemplateEngine templateEngine, String viewName) {
        if (StringUtils.isEmpty(viewName)) {
            throw new NutException("View Name Must Not Be Empty.");
        }
        this.viewName = viewName;
        this.templateEngine = templateEngine;
    }

    @Override
    public void render(Map<String, ?> model, Request request, Response response) throws Exception {
        WebRender webRender = new ThymeleafWebRender(templateEngine, getContentType(), model);
        webRender.render(viewName, request, response);
    }
}
